{layout name="../../admin/view/layout/main" /}
{if empty($iframe)}
    {:breadcrumb(['附件管理:attachment/index/index', '附件列表'])}
{/if}
<div class="row">
    <div class="col-lg-12">
        <div class="card">
            {if $iframe}
            <header class="card-header">
                <div class="card-title">附件列表</div>
            </header>
            {/if}
            <div class="card-body">
                <ul id="myTabs" class="nav nav-tabs" role="tablist">
                    <li class="nav-item"><a class="nav-link active" href="#photo" data-bs-toggle="tab"
                            onclick="goMedia('image')">图片</a></li>
                    <li class="nav-item"><a class="nav-link" href="#video" data-bs-toggle="tab"
                            onclick="goMedia('video')">视频</a></li>
                    <li class="nav-item"><a class="nav-link" href="#file" data-bs-toggle="tab"
                        onclick="goMedia('file')">文件</a></li>
                </ul>
                <div id="main-layer" style="display: flex; flex-direction: row;">
                    <div style="height: 100%; background: #f8f8f8; width: 240px; position: relative;"
                        class="lyear-scroll">
                        <!-- 左侧分类 -->
                        <div id="types-tree" style="padding: 10px;"></div>
                    </div>
                    <div style="width: 10px;"></div>
                    <div style="height: 100%; width: 100%; position: relative;" class="lyear-scroll">
                        <!-- 右侧内容 -->
                         <div style="position: relative;">
                            {if $iframe}
                            <button class="btn btn-success btn-sm" disabled id="select-btn" onclick="selectFiles();"><span class="mdi mdi-check"></span> 使用选中文件</button>
                            {/if}
                            <button class="btn btn-primary btn-sm" onclick="upload();"><span class="mdi mdi-upload"></span> 上传文件</button>
                            <button class="btn btn-danger btn-sm" disabled id="delete-btn" onclick="deleteAll();"><span class="mdi mdi-delete-outline"></span> 删除文件</button>
                            <button class="btn btn-primary btn-sm" disabled id="cat-btn" onclick="moveTo();"><span class="mdi mdi-arrow-right-thick"></span> 归类</button>
                            <div style="width: 250px; position: absolute; right: 0; top: 0;">
                                <div class="input-group">
                                    <input type="text" name="keywords" id="keywords" class="form-control" placeholder="文件名">
                                    <button type="button" class="btn btn-default" onclick="soso();">搜索</button>
                                    <button class="btn btn-default" onclick="location.reload();">
                                        重置
                                    </button>
                                  </div>
                            </div>
                         </div>
                         <div style="margin-top: 10px;">
                            <table id="table"></table>
                         </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="myModal" tabindex="-1" aria-labelledby="exampleModalLiveLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
      <div class="modal-content">
        <div class="modal-header">
          <h6 class="modal-title" id="exampleModalLiveLabel">归类</h6>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <form action="{:url('attachment/index/move')}" method="post" class="input-form needs-validation" novalidate>
          <input type="hidden" name="id" value="" id="post-id">
          <div class="modal-body">
            <div class="mb-3 row">
              <label for="pid" class="col-sm-3 col-form-label">移动至：<font color="red">*</font></label>
              <div class="col-sm-9">
                    <select class="form-select" name="pid" id="pid" required>
                        <option value="">-- 选择 --</option>
                    </select>
                </div>
            </div>
          </div>
          <div class="modal-footer">
              <button type="submit" class="btn btn-primary">确定</button>
              <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
          </div>
      </form>
      </div>
    </div>
  </div>

<script>
    var media_type = 'image';
    var media_cat_id = 0;
    var media_load = false;
    var selected = [];
    var myModal = null;
    var myMultiple = {$multiple};
    var fetch = false;
    function refreshTable(){
        $('#table').bootstrapTable('refresh', {
                url: "{:url('attachment/index/data')}?cat_id=" + media_cat_id + '&type=' + media_type,
            });
    }
    function soso(){
        var url = get_table_base_url('#table');
        var v = $('#keywords').val();
        $('#table').bootstrapTable('refresh', {
            url: url + '?keywords=' + v,
        });
    }
    function goMedia(type){
        fetch = false;
        media_type = type;
        media_cat_id = 0;
        selected = [];
        getCategory(type);
        if (media_load){
            refreshTable();
        }
    }
    function upload(){
        open_layer('上传文件', "{:url('attachment/index/upload')}?iframe=1&type=" + media_type + '&cat_id=' + media_cat_id, function (){
            refreshTable();
        }, ['80%', '480px']);
    }
    function getCategory(type){
        get_tree('#types-tree', '分类', {
            'list': "{:url('attachment/index/cateogry')}?type=" + type,
            'add': "{:url('attachment/index/add')}",
            'edit': "{:url('attachment/index/edit')}",
            'delete': "{:url('attachment/index/remove')}",
        }, {type: type}, function (selected){
            media_cat_id = selected.join(',');
            if (fetch){
                refreshTable();
            }else{
                if (media_cat_id != '0'){
                    fetch = true;
                    refreshTable();
                }
            }
        });
    }
    function editPost(id, value){
        layer.prompt({title: '重命名', formType: 0, value: value}, function(text, index){
            $.post("{:url('attachment/index/rename')}", { id: id, name: text }, function (){
                layer.close(index);
                $('#table').bootstrapTable('refresh');
            });
        });
    }
    function removePost(id){
        xp_confirm("{:url('attachment/index/delete')}", { id: id }, function (){
            selected = [];
            $('#table').bootstrapTable('refresh');
        }, '确认要删除吗？');
    }
    function deleteAll(){
        var id = selected.join(',');
        removePost(id);
    }
    function abc(){
        if (selected.length > 0) {
            $('#delete-btn, #cat-btn').removeAttr('disabled');
            var len = selected.length;
            if (myMultiple == 1 && len > 0) {
                $('#select-btn').removeAttr('disabled');
            }
            if (myMultiple == 0) {
                if (len == 1){
                    $('#select-btn').removeAttr('disabled');
                }else{
                    $('#select-btn').attr('disabled', 'disabled');
                }
            }
        }else{
            $('#delete-btn, #cat-btn, #select-btn').attr('disabled', 'disabled');
        }
    }
    function moveTo(){
        myModal.show();
        $('#post-id').val(selected.join(','));
        $.post("{:url('attachment/index/ajax_category')}", {type: media_type}, function (data) {
            $('#pid').html(`<option value="">-- 选择 --</option>` + data);
        });
    }
    function selectFiles(){
        var rows = $('#table').bootstrapTable('getData');
        var data = rows.filter(function(item){
            return selected.indexOf(item.id) >= 0;
        });
        var arr = [];
        if (data.length > 0){
            arr = data.map(function(item){
                return item.url;
            });
        }
        window.parent.{$callback}(arr.join(','));
    }
    $(function (){
        var windowHeight = window.innerHeight - {$height};
        $('#main-layer').height(windowHeight);
        myModal = new bootstrap.Modal($('#myModal'));
        validation_form('.input-form', function (){
            myModal.hide();
            selected = [];
            $('#table').bootstrapTable('refresh');
        });
        $('#table').bootstrapTable({
          classes: 'table table-bordered table-hover table-striped lyear-table',
          url: "{:url('attachment/index/data')}?cat_id=" + media_cat_id + '&type=' + media_type,
          pagination: true,
          search: false,
          pageSize: 20,
          sidePagination: 'server',
          checkbox: true,
          columns: [
                {field: 'example',
                    checkbox: true,
                    width: 5,
                    widthUnit: 'rem'
                },
              {'field': 'id', title: 'ID'},
              {'field': 'cat_name', title: '类别', formatter: function(value, item){
                if (value == '-'){
                    return '-';
                }
                return `<span class="badge bg-info">${value}</span>`;
              }},
              {'field': 'url', title: '预览', formatter: function(value, item){
                return `<a href="${value}" target="_blank"><img src="${value}" style="width: auto; height: 24px;" onerror="this.src='${item.icon}'"></a>`;
              }},
              {'field': 'filename', title: '文件名'},
              {'field': 'filesize', title: '文件大小'},
              {'field': 'create_time', title: '创建时间'},
              {'field': 'actions', title: '操作', formatter: function(value, item){
                if (item.id == 1){
                  return '-';
                }
                var dom = `<span class="badge bg-info" onclick="editPost('${item.id}', '${item.filename}');" style="cursor: pointer;"><span class="mdi mdi-square-edit-outline"></span> 编辑</span>`;
                dom = dom + `<span class="badge bg-danger" onclick="removePost('${item.id}');" style="cursor: pointer; margin-left: 5px;"><span class="mdi mdi-delete-outline"></span> 删除</span>`;
                return dom;
              }},
          ],
          onLoadSuccess: function (){
            selected = [];
          },
          onUncheck:function(row, $element){
                var id = row.id;
                if (selected.indexOf(id) >= 0){
                    selected.splice(selected.indexOf(id), 1);
                }
                abc();
            },
            onCheck:function(row, $element){
                var id = row.id;
                if (selected.indexOf(id) < 0){
                    selected.push(id);
                }
                abc();
            },
            onCheckAll: function (rowsAfter,rowsBefore) {
                if (rowsAfter.length > 0){
                    selected = rowsAfter.map(function (item) {
                        return item.id;
                    });
                }
                abc();
            },
            onUncheckAll: function (rowsAfter,rowsBefore) {
                selected = [];
                abc();
            }
      });
      goMedia('image');
      media_load = true;
    })
    </script>